package com.uduew.sjd.view.xpop

import android.content.Context
import android.view.View
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updateLayoutParams
import com.uduew.sjd.config.CameraDefine.CameraType
import com.uduew.sjd.R
import com.lxj.xpopup.core.BottomPopupView

class TakePhotoDialog(context: Context, private val mType: CameraType) : BottomPopupView(context) {
    var tvTakePhoto: TextView? = null
    var tvPhotoAlbum: TextView? = null
    var tvCancel: TextView? = null

    var clTakePic: ConstraintLayout? = null
    var clExample: ConstraintLayout? = null
    override fun getImplLayoutId(): Int {
        return R.layout.xpop_photo
    }

    var isApplyingInsets = false

    fun bottomInset(view: View) {

        ViewCompat.setOnApplyWindowInsetsListener(view) { v, insets ->
            if (isApplyingInsets) return@setOnApplyWindowInsetsListener insets
            isApplyingInsets = true
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.updateLayoutParams<MarginLayoutParams> {
                bottomMargin = systemBars.bottom
            }
            insets
        }
    }

    override fun onCreate() {
        super.onCreate()
        clTakePic = findViewById<ConstraintLayout?>(R.id.cl_take_pic)
        clExample = findViewById<ConstraintLayout?>(R.id.cl_example)

        if (mType == CameraType.Unknown) {
            clTakePic!!.visibility = GONE
            clExample!!.visibility = VISIBLE
        } else {
            clTakePic!!.visibility = VISIBLE
            clExample!!.visibility = GONE
        }

        tvTakePhoto = findViewById<TextView?>(R.id.tv_take_photo)
        tvPhotoAlbum = findViewById<TextView?>(R.id.tv_photo_album)
        tvCancel = findViewById<TextView?>(R.id.tv_cancel)
        tvCancel!!.setOnClickListener(OnClickListener { view: View? -> dismiss() })

        tvPhotoAlbum!!.setOnClickListener(object : OnClickListener {
            override fun onClick(view: View?) {
                if (onItemClickListener != null) {
                    onItemClickListener!!.onPhotoAlbumClick(mType)
                }
                dismiss()
            }
        })

        tvTakePhoto!!.setOnClickListener(OnClickListener { view: View? ->
            dismiss()
            if (onItemClickListener != null) {
                onItemClickListener!!.onTakePhotoClick(mType)
            }
        })
    }

    private var onItemClickListener: OnItemClickListener? = null

    fun setOnItemClickListener(listener: OnItemClickListener?) {
        this.onItemClickListener = listener
    }

    interface OnItemClickListener {
        fun onTakePhotoClick(type: CameraType)
        fun onPhotoAlbumClick(type: CameraType)
    }

}